#include"mystdio.h"


MYFILE* myfopen(const char *path, const char *mode)
{    
   int op_flag = 0; 
   int fd = 0;
   if(strcmp(mode,"w") == 0)
   {
      op_flag = O_CREAT | O_WRONLY | O_TRUNC;
      fd = open(path,op_flag,0666);
   }
   else if(strcmp(mode,"r") == 0)
   {
      op_flag = O_RDONLY;
      fd = open(path,op_flag);
   }
   if(fd < 0 )
     return NULL;
   MYFILE* fptr = (MYFILE*)malloc(sizeof(MYFILE));
   //初始化
   fptr->fd = fd;
   fptr->currant = 0;
   fptr->flag = FLUSH_LINE;
   memset(fptr->buff,0,sizeof(fptr->buff));
   return fptr;
  
}
int myfflush(MYFILE* fp)
{   
    if(fp == NULL)
    {
        perror("myfflush");
        exit(1);
    }
    write(fp->fd,fp->buff,fp->currant);
    fp->currant = 0;
    return 0;
}

int myfclose(MYFILE *fp)
{
  close(fp->fd);
  myfflush(fp);
  free(fp);
  fp = NULL;

  return 0;

}

size_t myfwrite(const void *ptr, size_t size, size_t nmem, MYFILE *fp)
{
  
    if(fp->currant == NUM)
    {
       myfflush(fp);
       return NUM-1;
    }
    size_t user_size = size * nmem;
    size_t rest_size = NUM-fp->currant;
    size_t writen = 0; //已经写的数据

    //把数据拷贝到缓冲区，有空间先考满，不刷新。
    if(user_size >= rest_size)
    {
      
        memcpy(fp->buff+fp->currant,ptr,rest_size);
        fp->currant += rest_size ; //currant指向最后一个数据的下一个
        writen = rest_size;
    }
    else
    {
        memcpy(fp->buff+fp->currant,ptr,user_size);
        fp->currant += user_size;
        writen = user_size;
    } 
  
    if(fp->flag == FLUSH_ALL)
    {
        if(fp->currant == NUM)
            myfflush(fp);
    }
    else if(fp->flag == FLUSH_LINE)
    {
        if(fp->buff[fp->currant-1] == '\n')
            myfflush(fp);
    }
    //刷新缓冲区
    return writen;
}

